import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import {
  Button,
  Flex,
  SegmentedControl,
  Toast,
  InputItem,
  List,
  Radio,
  Modal,
  WhiteSpace,
} from '@ant-design/react-native';
import { formatDate } from '@/helpers/dateutil';
import { IconX } from '@/rcomponents/iconx';
import Colors from '@/Themes/Colors';
import NumbericInputItem from '@/rcomponents/numbericInputItem';
import RnBarcodeScanner from './rnBarcodeScanner';
import RackMaterialStore from './rackMaterialStore';

const styles = StyleSheet.create({
  scanObj: {
    justifyContent: 'center',
    paddingHorizontal: 40,
    paddingBottom: 5,
  },
  scanIcon: {
    marginRight: 10,
  },
  descHeader: {
    backgroundColor: Colors.grey200,
    borderWidth: 1,
    borderColor: Colors.blueGrey100,
  },
  rackPartFlex: {
    alignItems: 'flex-start',
    justifyContent: 'center',
  },
  rackName: {
    color: 'red',
  },
  partNo: {
    color: 'aqua',
  },
  partNoSecond: {
    color: 'black',
  },
  earlierMaterialWarn: {
    fontWeight: 'bold',
    fontSize: 24,
  },
  earlierMaterialDesc: {
    color: Colors.red200,
    fontSize: 18,
  },
  scanMaterialStyle: {
    color: Colors.blue200,
    fontSize: 20,
  },
});

// 架位物料扫描页
function RackMaterialScanner({
  onExitScan,
  onMaterialScan,
  onChooseScannedMaterialQty,
}) {
  const [scanActionNum, setScanAction] = useState(0);
  const rackMaterialStore = RackMaterialStore.useStore();
  const { currentRack, scannedParts, partqtyModal } = rackMaterialStore;
  const [scanLoading, setScanLoading] = useState(false);
  const [scancode, setScanCode] = useState(null);
  useEffect(() => {
    return () => {
      rackMaterialStore.clearScannedData();
    };
  }, [rackMaterialStore]);
  const virtualStockReason = '虚占库存,无实物';
  const handleBarcodeRead = async (barcode) => {
    setScanLoading(true);
    if (scanActionNum === 0) {
      const rackRes = await rackMaterialStore.getRackByTid(barcode);
      if (rackRes.errorCode) {
        Toast.fail('扫码获取架位信息失败,请重试');
      } else {
        setScanAction(1);
      }
    } else {
      await onMaterialScan(currentRack, barcode, {
        reasonKind: 1,
        reasonDesc: virtualStockReason,
      });
    }
    setScanCode(barcode);
    setScanLoading(false);
  };
  if (partqtyModal.visible) {
    return (
      <Modal popup visible={partqtyModal.visible} animationType="slide-up">
        <List>
          {partqtyModal.earlierParts.length > 0 ? (
            <View>
              <Text style={styles.earlierMaterialWarn}>
                库存中有到期日期更早料件
              </Text>
              <Flex>
                <Flex.Item>
                  <Text style={styles.earlierMaterialDesc}>
                    {partqtyModal.earlierParts[0].part_no}
                  </Text>
                </Flex.Item>
                <Flex.Item>
                  <Text style={styles.earlierMaterialDesc}>
                    架位: {partqtyModal.earlierParts[0].rack_no}
                  </Text>
                </Flex.Item>
              </Flex>
              <Flex>
                <Flex.Item>
                  <Text style={styles.earlierMaterialDesc}>
                    到期日期:{' '}
                    {formatDate(
                      partqtyModal.earlierParts[0].expiry_time,
                      'YYYY-MM-DD',
                    )}
                  </Text>
                </Flex.Item>
                <Flex.Item>
                  <Text style={styles.earlierMaterialDesc}>
                    条形码: {partqtyModal.earlierParts[0].barcode}
                  </Text>
                </Flex.Item>
              </Flex>
              <Text style={styles.earlierMaterialWarn}>
                如继续选择此件,请选择理由
              </Text>
              <Text style={styles.earlierMaterialWarn}>
                系统会通知您的领导本次非规操作
              </Text>
              <WhiteSpace />
              <Text>选择理由</Text>
              <Radio.RadioItem
                checked={partqtyModal.reasonKind === 1}
                onChange={(event) => {
                  if (event.target.checked) {
                    rackMaterialStore.showPartQtyModal({
                      reasonKind: 1,
                      reasonDesc: virtualStockReason,
                    });
                  }
                }}
              >
                {virtualStockReason}
              </Radio.RadioItem>
              <Radio.RadioItem
                checked={partqtyModal.reasonKind === 2}
                onChange={(event) => {
                  if (event.target.checked) {
                    rackMaterialStore.showPartQtyModal({
                      reasonKind: 2,
                      reasonDesc: '',
                    });
                  }
                }}
              >
                其他
              </Radio.RadioItem>
              {partqtyModal.reasonKind === 2 && (
                <InputItem
                  value={partqtyModal.reasonDesc}
                  placeholder="填写理由"
                  onChange={(val) => {
                    rackMaterialStore.showPartQtyModal({
                      reasonDesc: val,
                    });
                  }}
                />
              )}
            </View>
          ) : null}
          <List.Item>
            <Text style={styles.scanMaterialStyle}>
              {partqtyModal.material.part_no}
            </Text>
          </List.Item>
          <List.Item>
            <Text style={styles.scanMaterialStyle}>
              系统批次号: {partqtyModal.material.batch_no}
            </Text>
          </List.Item>
          <List.Item>
            <Text style={styles.scanMaterialStyle}>
              可用数量: {partqtyModal.material.stock_qty}
            </Text>
          </List.Item>
          <NumbericInputItem
            value={partqtyModal.qty}
            minValue={1}
            maxValue={partqtyModal.material && partqtyModal.material.stock_qty}
            onChange={(val) => {
              const qty = Number(val);
              if (Number.isNaN(qty) || qty < 0) {
                Toast.fail('输入选择数量非法');
              } else if (qty > partqtyModal.material.stock_qty) {
                Toast.fail('输入选择数量超过扫码件库存数量');
              } else if (qty > 0) {
                rackMaterialStore.showPartQtyModal({
                  qty,
                });
              } else {
                rackMaterialStore.showPartQtyModal({
                  qty: '',
                });
              }
            }}
            label="选择数量"
          />
        </List>
        <Flex>
          <Flex.Item>
            <Button
              onPress={() => {
                rackMaterialStore.hidePartQtyModal();
              }}
            >
              取消
            </Button>
          </Flex.Item>
          <Flex.Item>
            <Button
              type="primary"
              onPress={() => {
                if (!partqtyModal.visible) {
                  return;
                } else if (
                  partqtyModal.earlierParts.length &&
                  !partqtyModal.reasonDesc
                ) {
                  Toast.fail('选择非更早件理由必填');
                } else if (!partqtyModal.qty) {
                  Toast.fail('选择数量必填');
                } else {
                  const scannedMaterial = {
                    ...partqtyModal.material,
                    special_reason: partqtyModal.reasonDesc,
                    qty: partqtyModal.qty,
                  };
                  rackMaterialStore.addScannedPart({
                    rack_no: partqtyModal.material.rack_no,
                    part_no: partqtyModal.material.part_no,
                    qty: partqtyModal.qty,
                  });
                  if (onChooseScannedMaterialQty) {
                    onChooseScannedMaterialQty(scannedMaterial);
                  }
                  rackMaterialStore.hidePartQtyModal();
                }
              }}
            >
              确定
            </Button>
          </Flex.Item>
        </Flex>
      </Modal>
    );
  }
  return (
    <RnBarcodeScanner
      topContent={
        <>
          <Flex style={styles.scanObj}>
            <IconX
              name="scan1"
              origin="ant"
              style={styles.scanIcon}
              size={32}
            />
            <Flex.Item>
              <SegmentedControl
                values={['扫架位', '扫料件']}
                selectedIndex={scanActionNum}
                onChange={(ev) => {
                  const segmentIndex = ev.nativeEvent.selectedSegmentIndex;
                  setScanAction(segmentIndex);
                  if (segmentIndex === 0) {
                    rackMaterialStore.clearScannedData();
                  }
                }}
              />
            </Flex.Item>
          </Flex>
          <Flex style={styles.rackPartFlex}>
            <Flex.Item>
              <Text style={styles.descHeader}>当前架位</Text>
              {!!currentRack.rackName && (
                <>
                  <Text style={styles.rackName}>{currentRack.rackName}</Text>
                  <Text style={styles.rackName}>{currentRack.shelfName}</Text>
                </>
              )}
            </Flex.Item>
            <Flex.Item>
              <Text style={styles.descHeader}>已扫料件</Text>
              {scannedParts.map((scr, idx) => (
                <Text
                  key={`${scr.part_no}${scr.rack_no}`}
                  style={idx === 0 ? styles.partNo : styles.partNoSecond}
                >
                  {scr.part_no} -- {scr.qty}件
                </Text>
              ))}
            </Flex.Item>
          </Flex>
        </>
      }
      scanProcessing={scanLoading}
      onExitScan={() => {
        onExitScan();
        rackMaterialStore.clearScannedData();
      }}
      onBarCodeRead={handleBarcodeRead}
      scannedBarcode={scancode}
    />
  );
}

export default RackMaterialScanner;
